<template>
  <div class="user-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <!-- 个人信息卡片 -->
        <el-card class="user-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" link @click="handleEditInfo">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
            </div>
          </template>
          <div class="user-info">
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar" />
              <el-upload
                class="avatar-uploader"
                action="/api/upload/avatar"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary" link>更换头像</el-button>
              </el-upload>
            </div>
            <div class="info-list">
              <div class="info-item">
                <span class="label">用户名：</span>
                <span>{{ userInfo.username }}</span>
              </div>
              <div class="info-item">
                <span class="label">昵称：</span>
                <span>{{ userInfo.nickname }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱：</span>
                <span>{{ userInfo.email || '未设置' }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <!-- 修改密码卡片 -->
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入原密码"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdatePassword" :loading="updating">
                更新密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑个人信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑个人信息"
      width="500px"
    >
      <el-form
        ref="infoFormRef"
        :model="infoForm"
        :rules="infoRules"
        label-width="100px"
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="infoForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="infoForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateInfo" :loading="updating">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

// 用户信息
const userInfo = reactive({
  username: '',
  nickname: '',
  email: '',
  avatar: ''
})

// 上传头像相关
const uploadHeaders = {
  Authorization: localStorage.getItem('token')
}

// 修改密码表单
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 修改密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度应在6-16个字符之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度应在6-16个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 编辑个人信息相关
const dialogVisible = ref(false)
const infoFormRef = ref(null)
const infoForm = reactive({
  nickname: '',
  email: ''
})

// 个人信息验证规则
const infoRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度应在2-10个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const updating = ref(false)

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await request.get('/user/info')
    if (res.code === 200) {
      Object.assign(userInfo, res.data)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 头像上传成功的回调
const handleAvatarSuccess = (res) => {
  if (res.code === 0) {
    userInfo.avatar = res.data
    ElMessage.success('头像更新成功')
  }
}

// 打开编辑对话框
const handleEditInfo = () => {
  infoForm.nickname = userInfo.nickname
  infoForm.email = userInfo.email
  dialogVisible.value = true
}

// 更新用户信息
const handleUpdateInfo = async () => {
  if (!infoFormRef.value) return
  
  await infoFormRef.value.validate(async (valid) => {
    if (valid) {
      updating.value = true
      try {
        const res = await request.patch('/user/update', {
          username: userInfo.username,
          nickname: infoForm.nickname,
          email: infoForm.email
        })
        
        if (res.code === 200) {
          ElMessage.success('个人信息更新成功')
          dialogVisible.value = false
          // 更新页面显示的用户信息
          await getUserInfo()
        } else {
          ElMessage.error(res.msg || '更新失败')
        }
      } catch (error) {
        ElMessage.error(error.msg || '更新失败')
      } finally {
        updating.value = false
      }
    }
  })
}

// 更新密码
const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      updating.value = true
      try {
        await request.patch('/user/updatePwd', null, {
          params: {
            oldPwd: passwordForm.oldPassword,
            newPwd: passwordForm.newPassword,
            rePwd: passwordForm.confirmPassword
          }
        })
        ElMessage.success('密码修改成功，请重新登录')
        localStorage.removeItem('token')
        window.location.href = '/login'
      } catch (error) {
        console.error('修改密码失败:', error)
      } finally {
        updating.value = false
      }
    }
  })
}

onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.user-card,
.password-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  text-align: center;
}

.avatar-container {
  margin-bottom: 20px;
}

.avatar-uploader {
  margin-top: 10px;
}

.info-list {
  text-align: left;
  padding: 0 20px;
}

.info-item {
  margin-bottom: 15px;
  font-size: 14px;
}

.info-item .label {
  color: #909399;
  margin-right: 10px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 